import { reqSendCode, reqRegister, reqLogin, reqGetUserInfo, reqLogout } from "@/api";
import { setToken, getToken, removeToken } from "@/utils/token";

const state = {
    code: '',
    token: getToken(),
    userInfo: {}
}
const mutations = {
    SENDCODE(state, code) {
        state.code = code
    },
    SETTOKEN(state, token) {
        state.token = token
    },
    SETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    CLEARALL(state) {
        state.userInfo = {};
        state.token = '';
        removeToken();
    }
}
const actions = {
    async sendCode({ commit }, phone) {
        let result = await reqSendCode(phone)
        if (result.code == 200) {
            commit("SENDCODE", result.data)
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    async register({ commit }, data) {
        let result = await reqRegister(data)
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    async login({ commit }, data) {
        let result = await reqLogin(data)
        if (result.code == 200) {
            commit("SETTOKEN", result.data.token)
            setToken(result.data.token)
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    async getUserInfo({ commit }) {
        let result = await reqGetUserInfo()
        if (result.code == 200) {
            commit("SETUSERINFO", result.data)
        }
    },
    async logout({ commit }) {
        let result = await reqLogout()
        console.log(result)
        if (result.code == 200) {
            commit("CLEARALL")
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    }
}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}